package cn.fl.ass.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.service.IAssVfInfoService;
import cn.fl.ass.service.IAssVfRtnLogService;
import cn.fl.ass.transform.AssVfRtnLogVOTransform;
import cn.fl.ass.vo.AssVfInfoVO;
import cn.fl.ass.vo.AssVfRtnLogVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import fl.ass.facade.condition.AssVfInfoQC;
import fl.ass.facade.condition.AssVfRtnLogQC;
import fl.ass.facade.constant.AssVfInfoConstant;
import fl.ass.facade.dto.AssVfRtnLogDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @Description: 资产核销信息表 控制层
 */
@Controller
@RequestMapping("/ass/assvfinfo")
public class AssVfInfoController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AssVfInfoController.class);

    @Autowired
    private IAssVfInfoService assVfInfoService;

    @Autowired
    private IAssVfRtnLogService assVfRtnLogService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("ass/assVfInfo/assVfInfoList");
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        List<KeyValueVO> isAllRtn = sysDictionaryApiService.getKvList(AssVfInfoConstant.IS_ALL_RTN_GRP_CD, AssVfInfoConstant.SYS_CD, AssVfInfoConstant.ORG_CD);
        String infoId = request.getParameter("id");
        ModelAndView view = new ModelAndView("ass/assVfInfo/assVfInfoView");
        view.addObject("infoId", infoId);
        view.addObject("isAllRtn", JSON.toJSON(isAllRtn));
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String infoId = request.getParameter("id");
        ModelAndView view = new ModelAndView("ass/assVfInfo/assVfInfoView");
        List<KeyValueVO> isAllRtn = sysDictionaryApiService.getKvList(AssVfInfoConstant.IS_ALL_RTN_GRP_CD, AssVfInfoConstant.SYS_CD, AssVfInfoConstant.ORG_CD);
        view.addObject("infoId", infoId);
        view.addObject("isAllRtn", JSON.toJSON(isAllRtn));
        view.addObject("detail", BaseConstant.IS_YESNO_YES_STR);
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 根据核销信息id查回款数据
     */
    @RequestMapping(value = "/searchRtnLogByInfoId.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object searchRtnLogByInfoId(HttpServletRequest request) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String infoId = request.getParameter("infoId");
        if (StringUtils.isEmpty(infoId)) {
            throw new BaseException("无资产核销主键");
        }
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        AssVfRtnLogQC assVfRtnLogQC = new AssVfRtnLogQC();
        assVfRtnLogQC.setVfInfoId(Long.valueOf(infoId));
        page.setCondition(assVfRtnLogQC);
        Pager pager = assVfRtnLogService.searchListPage(page);
        List<AssVfRtnLogDTO> resultList = (List<AssVfRtnLogDTO>) pager.getResultList();
        if (CollectionUtils.isNotEmpty(resultList)) {
            List<AssVfRtnLogVO> resultListVO = AssVfRtnLogVOTransform.toVOList(resultList);
            for (AssVfRtnLogVO assVfRtnLogVO : resultListVO) {
                assVfRtnLogVO.setRtnAmtYuan(DecimalUtils.convertFenToYuan(assVfRtnLogVO.getRtnAmt()));
            }
            ListPageVO<AssVfRtnLogVO> listPage = new ListPageVO<AssVfRtnLogVO>(resultListVO, pager.getTotalCount());
            return listPage;
        }
        ListPageVO<AssVfRtnLogVO> listPage = new ListPageVO<AssVfRtnLogVO>(null, pager.getTotalCount());
        return listPage;
    }

    /**
     * 初始化列表
     */
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String cstNm = request.getParameter("cstNm");
        String cntNo = request.getParameter("cntNo");
        String paySchNo = request.getParameter("paySchNo");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        AssVfInfoQC qc = new AssVfInfoQC();
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        if (StringUtils.isNotEmpty(cntNo)) {
            qc.setCntNo(cntNo);
        }
        if (StringUtils.isNotEmpty(paySchNo)) {
            qc.setPaySchNo(paySchNo);
        }
        page.setCondition(qc);
        Pager pager = this.assVfInfoService.searchListPage(page);
        List<AssVfInfoVO> list = (List<AssVfInfoVO>) pager.getResultList();
        ListPageVO<AssVfInfoVO> listPage = new ListPageVO<AssVfInfoVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 初始化核销明细和修改页面数据
     */
    @RequestMapping(value = "/initVfDetailData.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initVfDetailData(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "");
        String infoId = request.getParameter("infoId");
        if (StringUtils.isEmpty(infoId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        return assVfInfoService.getVfDetailViewData(Long.valueOf(infoId));
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        AssVfInfoVO entity = null;
        try {
            entity = new AssVfInfoVO();
            //TODO ADD PARAM
            Long id = this.assVfInfoService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "add", "新增数据.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("数据不存在!");
            BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        AssVfInfoVO entity = null;
        try {
            entity = new AssVfInfoVO();
            entity.setId(Long.valueOf(id));
            //entity.setName(name);
            //TODO ADD PARAM
            boolean success = this.assVfInfoService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.info(logger, "modify", "修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改成功.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 新增回款数据
     */
    @RequestMapping(value = "/saveRtnLogs.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object saveRtnLogs(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String rtnLogsList = request.getParameter("rtnList");
        String infoId = request.getParameter("infoId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        List<AssVfRtnLogVO> list = new ArrayList<AssVfRtnLogVO>();
        try {
            if (StringUtils.isNotBlank(rtnLogsList)) {
                list = JSON.parseArray(rtnLogsList, AssVfRtnLogVO.class);
                for (AssVfRtnLogVO assVfRtnLogVO : list) {
                    if (StringUtils.isEmpty(String.valueOf(assVfRtnLogVO.getRtnAmtYuan()))) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("有回款金额未填写，请填写后保存");
                        return result;
                    }
                    if (StringUtils.isEmpty(assVfRtnLogVO.getVfFundNo())) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("有资金编号未填写，请填写后保存");
                        return result;
                    }
                    if (StringUtils.isEmpty(assVfRtnLogVO.getIsAllRtn())) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("有是否全部回款未填写，请填写后保存");
                        return result;
                    }
                    if (null == assVfRtnLogVO.getRtnTm()) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("有回款时间未填写，请填写后保存");
                        return result;
                    }
                    assVfRtnLogVO.setRtnAmt(DecimalUtils.convertYuanToFen(assVfRtnLogVO.getRtnAmtYuan()));
                    assVfRtnLogVO.setVfInfoId(Long.valueOf(infoId));
                    assVfRtnLogVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                    assVfRtnLogVO.setMdfTm(Calendar.getInstance().getTime());
                    assVfRtnLogVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                }
            }
            this.assVfRtnLogService.addRtnLogs(list);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("新增回款记录数据失败").setKeys("list:" + JSON.toJSONString(list)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("新增回款记录数据失败").setKeys("list:" + JSON.toJSONString(list)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        }
        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeRtnLogByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeRtnLogByIds(HttpServletRequest request) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSON.parseArray(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
        try {
            boolean success = this.assVfRtnLogService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("删除资产核销记录数据失败").setKeys("ids：" + idsList.toString()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("删除资产核销记录数据失败").setKeys("ids：" + idsList.toString()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            AssVfInfoVO vo = this.assVfInfoService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 批量导入移交申请数据
     *
     * @throws Exception
     */
    @RequestMapping(value = "/importVFInfo.do")
    @ResponseBody
    public Object importBatchTransfer(@RequestParam(value = "upfile") MultipartFile upfile, HttpServletRequest request) throws Exception {
        BaseLogUtils.newLogger("上传文件：" + JSON.toJSONString(upfile) + "文件名称：" + upfile.getOriginalFilename()).info();
        try {
            DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "导入成功");
            if (null == upfile) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("模板文件为空,请选择文件");
                return result;
            }
            String fileName = upfile.getOriginalFilename();
            String[] names = fileName.split("\\.");
            if (!names[names.length - 1].toLowerCase().equals("xls")) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("请下载模板，然后填写数据!!");
                return result;
            }
            InputStream fis = upfile.getInputStream();
            // * 成功失败标识  1成功  0失败
            result = this.assVfInfoService.parseExcel(fis, result);
            if (BaseConstant.IS_YESNO_NO == result.getSuccess()) {
                return result;
            }
            // 解析到的数据（Excel中支付表号）
            List<String> paySchNos = (List<String>) result.getData();
            boolean success = assVfInfoService.handlePaySchNosAndInsertVfInfo(paySchNos, CurrentThreadContext.getCurrentUserId());
            if (false == success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
            }
            return result;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("批量导入移交申请数据错误:" + JSON.toJSONString(upfile)).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }  catch (Exception e) {
            BaseLogUtils.newLogger("批量导入移交申请数据错误:" + JSON.toJSONString(upfile)).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

}

